package com.jackrain.nea.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.core.schema.*;
import com.jackrain.nea.core.webaction.WebAction;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.query.QuerySession;
import com.jackrain.nea.web.query.QueryUtils;
import com.jackrain.nea.web.query.SubSystemView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Controller
public class ResthomeController {
    
    private SubSystemView subSystemView = new SubSystemView();
    ;
    
    
    @RequestMapping(value = "/p/cs/resthome", method = RequestMethod.GET)
    public String hello(HttpServletRequest request, Model pmodel) throws Exception {
        
        User userWeb = (UserImpl) request.getSession().getAttribute("user");
        
        QuerySession qsession = QueryUtils.createQuerySession(userWeb);
        TableManager tm = qsession.getTableManager();
        
        
        List<ArrayList> list = tm.getSubSystems();
        
        JSONArray subs = new JSONArray();
        for (Object sub : list) {
            JSONObject subJO = new JSONObject();
            subJO.put("id", ((SubSystem) sub).getId());
            subJO.put("value", ((SubSystem) sub).getId());
            subJO.put("label", ((SubSystem) sub).getName());
            subJO.put("level", "SubSystem");
            JSONArray categorys = new JSONArray();
            for (TableCategory category : ((SubSystem) sub).getTableCategories()) {
                JSONObject categoryJO = new JSONObject();
                categoryJO.put("id", category.getId());
                categoryJO.put("value", category.getId());
                categoryJO.put("label", category.getDescription(userWeb.getLocale()));
                categoryJO.put("level", "TableCategory");
                List lists = category.children();
                JSONArray children = new JSONArray();
                for (Object o : lists) {
                    JSONObject jo = new JSONObject();
                    if (o instanceof Table) {
                        jo.put("id", ((Table) o).getId());
                        jo.put("value", ((Table) o).getName());
                        jo.put("label", ((Table) o).getDescription(userWeb.getLocale()));
                        jo.put("type", "table");
                    } else if (o instanceof WebAction) {
                        if (((WebAction) o).getDisplayType().equals(WebAction.DisplayTypeEnum.Accord)) {
                            jo.put("id", ((WebAction) o).getId());
                            jo.put("value", ((WebAction) o).getName());
                            jo.put("label", ((WebAction) o).getDescription(userWeb.getLocale()));
                            jo.put("webaction", JSON.parseObject(((WebAction) o).getScript()));
                            jo.put("type", "action");
                        }
                    }
                    children.add(jo);
                }
                categoryJO.put("children", children);
                categorys.add(categoryJO);
            }
            subJO.put("children", categorys);
            subs.add(subJO);
        }
        
        
        pmodel.addAttribute("model", subs);
        return "resthome";
    }
    
    
    @RequestMapping(path = "/p/cs/rest", method = {RequestMethod.GET, RequestMethod.POST})
    public String restinfo(HttpServletRequest request, Model pmodel, @RequestParam(value = "table", required = true) int tableId) throws Exception {
        
        
        User userWeb = (UserImpl) request.getSession().getAttribute("user");
        
        QuerySession qsession = QueryUtils.createQuerySession(userWeb);
        TableManager tm = qsession.getTableManager();
        Table table = tm.getTable(tableId);
        
        JSONObject tabObj = new JSONObject();
        
        tabObj.put("tableid", table.getId());
        tabObj.put("tablename", table.getName());
        tabObj.put("tabledesc", table.getDescription(qsession.getLocale()));
        tabObj.put("ismenu", table.isMenuObject());
        tabObj.put("isview", table.isView());
        
        if (table.isView()) {
            Table rt = tm.getTable(table.getRealTableName());
            tabObj.put("rtname", rt.getRealTableName());
            tabObj.put("rtdesc", rt.getDescription(qsession.getLocale()));
            tabObj.put("rttabid", rt.getId());
        }
        
        
        tabObj.put("tabcomment", table.getComment());
        
        tabObj.put("pk", table.getPrimaryKey().getName());
        tabObj.put("ak", table.getAlternateKey().getName() + " " + table.getAlternateKey().getDescription(qsession.getLocale()) + " " + table.getInputBoxIndicator(table.getAlternateKey(), qsession.getLocale()));
        tabObj.put("isadd", table.isActionEnabled(Table.ADD));
        tabObj.put("ismod", table.isActionEnabled(Table.MODIFY));
        tabObj.put("isdel", table.isActionEnabled(Table.DELETE));
        tabObj.put("issubmit", table.isActionEnabled(Table.SUBMIT));
        
        JSONArray reftabs = new JSONArray();
        ArrayList rbts = table.getRefByTables();
        for (int i = 0; i < rbts.size(); i++) {
            RefByTable rbt = (RefByTable) rbts.get(i);
            Table rbtt = tm.getTable(rbt.getTableId());
            
            JSONObject reftabObj = new JSONObject();
            
            reftabObj.put("tableid", rbtt.getId());
            reftabObj.put("tablename", rbtt.getName());
            reftabObj.put("tabledesc", rbtt.getDescription(qsession.getLocale()));
            reftabObj.put("tabrelation", (rbt.getAssociationType() == RefByTable.ONE_TO_MANY ? "1:m" : "1:1"));
            
            reftabs.add(reftabObj);
        }
        
        if (reftabs.size() > 0) {
            tabObj.put("reftabs", reftabs);
        }
        
        
        JSONArray webactions = new JSONArray();
        List<WebAction> actions = table.getWebActions(WebAction.DisplayTypeEnum.ObjButton);
        List<WebAction> was = table.getWebActions(WebAction.DisplayTypeEnum.ObjMenuItem);
        ArrayList actions2 = new ArrayList();
        for (int wasi = 0; wasi < actions.size(); wasi++) {
            WebAction wa = actions.get(wasi);
            actions2.add(wa);
        }
        for (int wasi = 0; wasi < was.size(); wasi++) {
            WebAction wa = was.get(wasi);
            actions2.add(wa);
        }
        
        for (int i = 0; i < actions2.size(); i++) {
            WebAction act = (WebAction) actions2.get(i);
            webactions.add(act);
        }
        
        if (webactions.size() > 0) {
            tabObj.put("webactions", webactions);
        }
        
        
        if (table.isActionEnabled(Table.ADD)) {
            
            ArrayList columns = table.getColumns(new int[]{1}, true, userWeb.getSecurityGrade());
            
            tabObj.put("addcolumns", columns);

            JSONObject jor=new   JSONObject();
            
            columns.forEach(item->{
                jor.put(((Column)item).getName(),"");
            });
            
            tabObj.put("addobjs", jor);
        }
        
        
        if (table.isActionEnabled(Table.MODIFY)) {
            
            ArrayList columns = table.getColumns(new int[]{3}, true, userWeb.getSecurityGrade());
            
            tabObj.put("modcolumns", columns);

            JSONObject jor=new   JSONObject();

            columns.forEach(item->{
                jor.put(((Column)item).getName(),"' '");
            });

            tabObj.put("modobjs", jor);
        }
        
        ArrayList indexcol = table.getColumns(new int[]{1, 3, 4}, true, userWeb.getSecurityGrade());
        
        tabObj.put("indexcolumns", indexcol);


        ArrayList allcol = table.getAllColumns();

        tabObj.put("allcolumns", allcol);
        
        
        
        
        pmodel.addAttribute("model", tabObj);
        
        return "rest";
    }
    
    
}
